【JavaSE】Java基础语法(四十二):NIO |
您所在的位置:网站首页 › java nio 书籍 › 【JavaSE】Java基础语法(四十二):NIO |
文章目录
1. 概述2. NIO与BIO的区别3. NIO三大模块4. NIO创建缓冲区对象【应用】5. NIO缓冲区添加数据【应用】6. NIO缓冲区获取数据【应用】7. 小结
方法介绍 代码示例 public class CreateByteBufferDemo1 { public static void main(String[] args) { //method1(); //method2(); ByteBuffer wrap = ByteBuffer.wrap("aaa".getBytes()); for (int i = 0; i byte [] bytes = {97,98,99}; ByteBuffer byteBuffer2 = ByteBuffer.wrap(bytes); //缓冲区的长度3 //缓冲区里面的内容就是字节数组的内容. for (int i = 0; i ByteBuffer byteBuffer1 = ByteBuffer.allocate(5); //get for (int i = 0; i public static void main(String[] args) { // int position() 当前要操作的索引 // int limit() 最多能操作到哪个索引 // int capacity() 缓冲区的总长度 ByteBuffer byteBuffer = ByteBuffer.allocate(10); System.out.println(byteBuffer.position());//0 System.out.println(byteBuffer.limit());//10 System.out.println(byteBuffer.capacity());//10 // put(byte b) 一次添加一个字节 // byteBuffer.put((byte) 97); // System.out.println(byteBuffer.position()); // System.out.println(byteBuffer.limit()); // System.out.println(byteBuffer.capacity()); // put(byte[] src) 一次添加一个字节数组 // byteBuffer.put("aaa".getBytes()); // System.out.println(byteBuffer.position());//3 // System.out.println(byteBuffer.limit());//10 // System.out.println(byteBuffer.capacity());//10 // position(int newPosition) 修改position // byteBuffer.position(1); // limit(int newLimit) 修改limit // byteBuffer.limit(5); // System.out.println(byteBuffer.position()); // System.out.println(byteBuffer.limit()); // System.out.println(byteBuffer.capacity()); // int remaining() 还有多少能操作 // boolean hasRemaining() 是否还有能操作的 byteBuffer.put("0123456789".getBytes()); System.out.println(byteBuffer.remaining()); System.out.println(byteBuffer.hasRemaining()); } } 6. NIO缓冲区获取数据【应用】方法介绍 代码示例 public class ByteBufferDemo3 { public static void main(String[] args) { ByteBuffer byteBuffer = ByteBuffer.allocate(10); byteBuffer.put("abc".getBytes()); // flip() 切换读写模式(写读) byteBuffer.flip(); // get() 读一个字节 // while(byteBuffer.limit() != byteBuffer.position()){ // System.out.println((char) byteBuffer.get()); // } for (int i = 0; i // System.out.println((char) byteBuffer.get()); // } // clear() 数据读写完毕(读->写) byteBuffer.clear(); byteBuffer.put("qqq".getBytes()); // array() 将缓冲区转换成字节数组返回 byte[] bytes = byteBuffer.array(); System.out.println(new String(bytes)); } } 7. 小结1. 需求:我要把数据写到缓冲区中。 数据是从外面进入到缓冲区的,所以缓冲区在做读数据的操作。 2. 需求:我要把数据从缓冲区中读出来。 数据是从缓冲区里面到外面的。所以缓冲区在做写数据的操作。 3. capacity:容量(长度) limit: 界限(最多能读/写到哪里) posotion:位置(读/写哪个索引) 获取缓冲区里面数据之前,需要调用flip方法 再次写数据之前,需要调用clear方法, 但是数据还未消失,等再次写入数据,被覆盖了才会消失。 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |